﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CsharpTpl.model;
using Lephone.Data;
using XPTable.Models;
using XPTable.Renderers;
using XPTable.Editors;
using Lephone.Data.SqlEntry;

namespace CsharpTpl.window
{
    public partial class FrmDMBMX : Form
    {
        private T_DMBMC _DMBMC;
        private List<WHZD> _WHZDS;
        private Dictionary<int, string[]> editorItems = new Dictionary<int,string[]>();
        public FrmDMBMX()
        {
            InitializeComponent();
            _LoadDMList();
            ImageList ilist = new ImageList();
            ilist.ImageSize = new Size(1, 20);
            listView1.SmallImageList = ilist;
            listView1.Columns[1].Width = 130;
        }
        protected override void OnLoad(EventArgs e)
        {
            table1.GridLines = GridLines.Both;
            table1.SelectionStyle = SelectionStyle.ListView;
            table1.EditStartAction = EditStartAction.SingleClick;
            table1.HeaderRenderer = new GradientHeaderRenderer();
            tableModel1.RowHeight = 20; 
        }
        void _LoadDMList()
        {
            listView1.Items.Clear();
            List<T_DMBMC> dmbmcs = T_DMBMC.FindAll(new OrderBy("DMJX"));
            ListViewItem item;
            foreach (T_DMBMC dmbmc in dmbmcs)
            {
                item = new ListViewItem(dmbmc.DMJX);
                item.SubItems.Add(dmbmc.DMMC);
                listView1.Items.Add(item);
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                table1.BeginUpdate();
                columnModel1.Columns.Clear();
                
                ListViewItem item = listView1.SelectedItems[0];
                _DMBMC = T_DMBMC.FindOne(CK.K["DMJX"] == item.Text);
                _WHZDS = LitJson.JsonMapper.ToObject<List<WHZD>>(_DMBMC.WHZD);
                _WHZDS.Sort();
                int i = 1;
                DataSet ds;
                List<string> comboxItems;
                editorItems.Clear();
                TextColumn idColumn = new TextColumn("ID");
                idColumn.Editable = false;
                columnModel1.Columns.Add(idColumn);
                foreach (WHZD zd in _WHZDS)
                {
                    switch (zd.KJLX)
                    {
                        case "文本框":
                            columnModel1.Columns.Add(new TextColumn(zd.MC));
                            break;
                        case "下拉框":
                            columnModel1.Columns.Add(new ComboBoxColumn(zd.MC));
                            switch (zd.DMLX)
                            {
                                case "SQL":
                                    ds = DbEntry.Context.ExecuteDataset(new SqlStatement(zd.DM));
                                    comboxItems = new List<string>();
                                    foreach (DataRow r in ds.Tables[0].Rows)
                                    {
                                        comboxItems.Add(r[0].ToString());
                                    }
                                    editorItems.Add(i, comboxItems.ToArray());
                            	    break;
                                case "自定义":
                                    comboxItems = new List<string>();
                                    foreach (string itm in zd.DM.Split(new char[] { '|' }))
                                    {
                                        comboxItems.Add(itm);
                                    }
                                    editorItems.Add(i, comboxItems.ToArray());
                                    break;
                            }
                            break;
                        case "日期":
                            DateTimeColumn dtc = new DateTimeColumn(zd.MC);
                            dtc.Width = 160;
                            columnModel1.Columns.Add(dtc);
                            break;
                    }
                    i++;
                }
                _LoadDMBMXList();
                table1.EndUpdate();
            }
        }
        /************************************************************************/
        /* 加载明细列表                                                                     */
        /************************************************************************/
        void _LoadDMBMXList()
        {
            table1.BeginUpdate();
            tableModel1.Rows.Clear();
            List<Cell> cells;
            DataSet ds = DbEntry.Context.ExecuteDataset("select * from t_dmbxx where dmmc='" + _DMBMC.DMJX + "' order by sxh");
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                cells = new List<Cell>();
                cells.Add(new Cell(dr["ID"].ToString()));
                Cell cell=null;
                foreach (WHZD whzd in _WHZDS)
                {
                    if (whzd.KJLX.Equals("日期"))
                    {
                        cell = new Cell();
                        cell.Data = DateTime.Parse(string.Format("{0:0000-00-00 00:00:00}",long.Parse(dr[whzd.ZD.ToString()].ToString())));
                    }
                    else
                    {
                        cell = new Cell(dr[whzd.ZD.ToString()].ToString());
                    }
                    cells.Add(cell);
                }
                tableModel1.Rows.Add(new Row(cells.ToArray()));
            }
            table1.EndUpdate();
        }
        /************************************************************************/
        /* 添加一条新记录,默认值都为空                                                                     */
        /************************************************************************/
        private void button1_Click(object sender, EventArgs e)
        {
            table1.BeginUpdate();
            List<Cell> cells = new List<Cell>();
            cells.Add(new Cell());
            foreach (WHZD whzd in _WHZDS)
            {
                cells.Add(new Cell(""));
            }
            tableModel1.Rows.Add(new Row(cells.ToArray()));
            table1.EndUpdate();
        }

        private void table1_BeginEditing(object sender, XPTable.Events.CellEditEventArgs e)
        {
            if (e.Editor is ComboBoxCellEditor)
            {
                ((ComboBoxCellEditor)e.Editor).Items.Clear();
                try
                {
                    ((ComboBoxCellEditor)e.Editor).Items.AddRange(editorItems[e.Column]);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("初始化列表错误,请确认该字段正确设置!");
                }
                
            }
        }
        /************************************************************************/
        /* 保存数据列表                                                                     */
        /************************************************************************/
        private void button3_Click(object sender, EventArgs e)
        {
            T_DMBXX dmbxx;
            foreach (Row r in tableModel1.Rows)
            {
                dmbxx = T_DMBXX.New;
                if (!string.IsNullOrEmpty(r.Cells[0].Text))
                    dmbxx.Id = long.Parse(r.Cells[0].Text);
                dmbxx.DMMC = _DMBMC.DMJX;
                for (int i = 0; i < _WHZDS.Count;i++ )
                {
                    string value="";
                    if (_WHZDS[i].KJLX.Equals("日期"))
                    {
                        try
                        {
                            value = ((DateTime)r.Cells[i + 1].Data).ToString("yyyyMMddHHmmss");
                        }
                        catch (System.Exception ex)
                        {
                        	
                        }
                    }
                    else
                    {
                        value = r.Cells[i+1].Text;
                    }
                    switch (_WHZDS[i].ZD)
                    {
                        case "VALUE":
                            dmbxx.VALUE = value;
                            break;
                        case "SXH":
                            try
                            {
                                dmbxx.SXH = int.Parse(value);
                            }
                            catch (FormatException ex)
                            {
                                dmbxx.SXH = 0;
                            }
                            break;
                        case "TEXTA":
                            dmbxx.TEXTA = value;
                            break;
                        case "TEXTB":
                            dmbxx.TEXTB = value;
                            break;
                        case "TEXTC":
                            dmbxx.TEXTC = value;
                            break;
                        case "TEXTD":
                            dmbxx.TEXTD = value;
                            break;
                        case "TEXTE":
                            dmbxx.TEXTE = value;
                            break;
                        case "ZT":
                            if (value.Equals("启用"))
                            {
                                dmbxx.ZT=1;
                            } 
                            else
                            {
                                dmbxx.ZT=0;
                            }
                            break;
                    }
                }
                dmbxx.Save();
            }
            _LoadDMBMXList();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (table1.SelectedItems.Length > 0)
            {
                if (MessageBox.Show(this, "确认要删除此项记录么?此操作无法恢复.", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Row r = table1.SelectedItems.First();
                    DbEntry.Context.ExecuteNonQuery("delete from t_dmbxx where id='" + r.Cells[0].Text + "'");
                    _LoadDMBMXList();
                }
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Console.Write(tboxFilter.Text);
            foreach (ListViewItem item in listView1.Items)
            {
                if (string.IsNullOrEmpty(tboxFilter.Text))
                {
                    item.BackColor = Color.White;
                }
                else if (item.Text.StartsWith(tboxFilter.Text.Trim()))
                {
                    item.BackColor = Color.Blue;
                }
            }
        }
    }
}
